package com.machinecontroller.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.machinecontroller.constant.McConfig;
import com.machinecontroller.constant.UrlConstant;
import com.machinecontroller.model.ReceiverModel;
import com.machinecontroller.model.ResultModel;
import com.machinecontroller.utils.DevUtil;
import com.machinecontroller.utils.EVControlerUtil;
import com.machinecontroller.utils.GsonUtil;
import com.machinecontroller.utils.Logger;
import com.sunshine.retrofit.HttpBuilder;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by zhangxuehui on 2017/12/17.
 */

public class JPushBroadCastReceiver extends BroadcastReceiver {
    private static final String TAG = "JIGUANG-Example";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            Logger.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                Logger.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知");
                try {
                    String json = getJson(bundle);
                    Gson gson = new Gson();
                    ReceiverModel mModel = gson.fromJson(json, ReceiverModel.class);
                    int addr = Integer.parseInt(mModel.getResult().getAddr());
                    int boxNo = Integer.parseInt(mModel.getResult().getBox());
                    //尝试3次，如果还是失败，上传报错信息
                    if (!EVControlerUtil.openDoor(addr, boxNo)) {
                        Map<String, String> map = new HashMap<>();
                        String imei = DevUtil.getImei(context);
                        map.put("version", DevUtil.getVersion(context));
                        map.put("devid", TextUtils.isEmpty(imei) ? "" : imei);
                        map.put("bno", boxNo + "");
                        map.put("status", 1 + "");
                        new HttpBuilder(UrlConstant.API_SEND_DOOR_STATUS)
                                .params(map)
                                .success(str -> {//请求成功返回的数据
                                    Log.e(TAG, str);
                                    ResultModel model = GsonUtil.praseModel(str, ResultModel.class);
                                    if (model != null) {
                                        if (model.getCode().equals("0")) {
                                            Logger.e(TAG, "门状态上报成功");
                                            return;
                                        }
                                    }
                                    Logger.e(TAG, "门状态返回异常");
                                })
                                .error(e -> {//请求失败返回的数据
                                    Log.e(TAG, "门状态返回异常 ==> " + e.toString());
                                })
                                .get();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 用户点击打开了通知");
            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Logger.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                Logger.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {

        }

    }

    // 返回的json数据
    private static String getJson(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_ALERT)) {
                sb.append(bundle.getString(key));
            }
        }
        return sb.toString();
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Logger.i(TAG, "This message has no Extra data");
                    continue;
                }
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

}
